package shop.utils;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

//加密密码
public class MD5Util {
    /**
     * 获取字符串的MD5哈希值
     *
     * @param input 输入字符串
     * @return 字符串的MD5哈希值
     */
    public static String getMD5(String input) {
        try {
            // 创建MessageDigest实例并初始化为MD5算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 将输入字符串转换为字节数组
            byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));
            // 将字节数组转换为十六进制字符串
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            // 确保哈希字符串长度为32
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // 使用示例
        String input = "123456";
        String md5Hash = MD5Util.getMD5(input);
        System.out.println("MD5 Hash of \"" + input + "\": " + md5Hash);
    }
}
